var url = 'ws://' + location.host;
var ws = new WebSocket(url);

var app = new Vue({
    el: '#app',
    data: {
        uuid: '', // 身份ID
        wsStatus: 0, // 连接状态 0连接中 1连接成功 2连接断开
        onlineNum: 0, // 在线人数
        isWhispers: false, // 是否悄悄话
        content: '', // 内容
        chatList: [], // 聊天列表
        userInfo: {}, // 用户信息
    },
    mounted() {
        this.uuid = this.getRandom();
        this.getUserInfo();
        this.initData();
    },
    methods: {
        // 生成随机数
        getRandom() {
            var uuid = localStorage.getItem('UUID');
            if (uuid) return uuid;

            function SJ() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            var random = (SJ() + SJ() + "-" + SJ() + "-" + SJ() + "-" + SJ() + "-" + SJ() + SJ() + SJ());
            localStorage.setItem('UUID', random);
            return random;
        },

        // 获取用户信息
        async getUserInfo() {
            const res = await axios.get('/api/getUserInfo?uuid=' +  this.uuid).then(res => {
                return res.data;
            });

            if (res.code !== 0) return;

            this.userInfo = res.data;
        },

        // 初始化数据
        initData() {
            var that = this;
            // 监听是否已连接
            ws.onopen = function (e) {
                that.wsStatus = 1;
            }

            // 监听连接是否已关闭
            ws.onclose = function (e) {
                that.wsStatus = 2;
            }

            // 监听接受到的消息
            ws.onmessage = function (res) {
                var data = JSON.parse(res.data || '{}');

                // 历史消息
                var history = JSON.parse(data.history || '[]');
                if (history.length) {
                    var chatList = that.chatList;
                    that.chatList = that.handleHistoryMsg(history).concat(chatList);
                }

                // 在线人数
                var totalPeople = data.totalPeople || 0;
                if (that.onlineNum !== totalPeople) {
                    that.onlineNum = totalPeople;
                }

                // 消息内容
                var msg = data.content || '';
                var image = data.image || '';
                if (msg || image) {
                    that.chatList.push({
                        uuid: data.uuid,
                        nickname: data.nickname,
                        avatar: data.avatar,
                        contents: msg ? msg.split(/[\n]/) : [],
                        image: image,
                        createTime: that.getTimeDesc(data.createDate)
                    });
                }

                that.onScrollBottom();
            }
        },

        // 滚动条置底
        onScrollBottom() {
            setTimeout(() => {
                var chatBox = this.$refs.chat;
                if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
            }, 0)
        },

        // 处理历史消息
        handleHistoryMsg(list) {
            return list.map(item => {
                return {
                    uuid: item.uuid,
                    nickname: item.nickname,
                    avatar: item.avatar,
                    contents: item.content ? item.content.split(/[\n]/) : [],
                    image: item.image || '',
                    createTime: this.getTimeDesc(item.createDate)
                }
            })
        },

        // 获取时间描述
        getTimeDesc(timestamp) {
            if (!timestamp) return '';

            var curDate = this.timeStampToTime(Number(new Date()), '.');
            var msgDate = this.timeStampToTime(timestamp, '.');

            if (curDate.slice(0, 10) === msgDate.slice(0, 10)) {
                return msgDate.slice(11);
            }

            if (curDate.slice(5, 10) === msgDate.slice(5, 10)) {
                return msgDate.slice(5, 11);
            }

            return msgDate;
        },

        // 时间戳转时间
        timeStampToTime(timestamp, symbol = '-') {
            var now = new Date(timestamp),
                y = now.getFullYear(),
                m = now.getMonth() + 1,
                d = now.getDate();
            return y + symbol + (m < 10 ? "0" + m : m) + symbol + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
        },

        // 选择图片
        async onChooseImage(e) {
            var that = this;
            var file = event.target.files[0];
            var tempUrl = URL.createObjectURL(file);

            // 表单置空
            var fileInput = this.$refs.file;
            fileInput.value = '';

            // 默认展示（调上传接口后再删除）
            var chatList = that.chatList;
            var random = that.getRandom();
            chatList.push({
                tempId: random,
                uuid: that.uuid,
                contents: [],
                image: tempUrl,
                ...that.userInfo,
            })

            that.onScrollBottom();

            // 上传图片至服务器
            var formData = new FormData();
            formData.append('image', file);
            var similar = await this.getImageData(tempUrl);
            formData.append('similar', similar);

            var res = await this.uploadImage(formData);

            var delIdx = -1;
            chatList.map((item, index) => {
                if (item.tempId === random) {
                    delIdx = index
                }
            })

            if (delIdx > -1) chatList.splice(delIdx, 1);

            if (res.code === 0) {
                // 发送图片消息
                var imgUrl = res.data.path.replace(/\\/g, '/');
                ws.send(JSON.stringify({
                    uuid: that.uuid,
                    content: '',
                    image: imgUrl,
                    whispers: that.isWhispers
                }));

            } else {
                alert(res.msg || '图片上传失败');
            }
        },

        // 获取图片数据
        getImageData(src) {
            return new Promise(resolve => {
                var image = new Image();
                image.src = src;
                image.onload = function() {
                    resolve(searchImage(image))
                }
            })
        },

        // 上传图片
        async uploadImage(params) {
            let requestObj = {
                method: "POST",
                url: "/api/upload/image",
                data: params,
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            };

            return await axios(requestObj).then(res => {
                return res.data;
            }).catch(function (error) {
                return '';
            });
        },

        // 发送消息
        sendMsg() {
            var that = this;
            if (that.wsStatus !== 1) {
                alert('未建立连接');
                return;
            }
            var content = that.content;
            if (!content.trim()) return;

            ws.send(JSON.stringify({
                uuid: that.uuid,
                content,
                image: '',
                whispers: that.isWhispers
            }));

            that.content = '';
        }
    }
})